
<template>
  <div class="center-camera" id="center-camera">
    <el-image-viewer :urlList='imgList' v-if="showViewer" :on-close="closeImg"></el-image-viewer>
    <div class="screen-menu">
      <!-- <span class="menu-num stream-btn" :class="{active: bitStreamType === 1}" @click="changeBitType(1)">高码流</span>
      <span class="menu-num stream-btn" :class="{active: bitStreamType === 0}" @click="changeBitType(0)">低码流</span> -->
      <!-- <span class="menu-num stream-btn" @click="videoConfig">播放设置</span> -->
      <span class="menu-num stream-btn" @click="getfullScreen">全 屏</span>
      <!-- <span class="menu-num stream-btn" @click="stop">停止</span> -->

      <span class="menu-num" :class="{active: curerntSelect == 'one'}" @click="changeScreen('one')">单屏</span>
      <span class="menu-num" :class="{active: curerntSelect == 'four'}" @click="changeScreen('four')">四分屏</span>
      <span class="menu-num" :class="{active: curerntSelect == 'six'}" @click="changeScreen('six')">六分屏</span>
      <!-- <span class="menu-num" :class="{active: curerntSelect == 'nine'}" @click="changeScreen('nine')">九分屏</span> -->
    </div>

    <div class="screen" :class="{'full-screen':fullScreen}" id="screen" ref="screen">
      <i v-if="fullScreen" class="el-icon-close close-btn" @click.stop="closeFullScreen"></i>
      <a ref="download" href="#" style="display: none;position:absolute;" download></a>
      <div class="list" :class="[`list-${curerntSelect}`]" v-for="(item, index) in screenList" :key='index'>
        <!-- v-loading="loadingCamera[index]" -->
        <div :class="{'current-screen': currentScreen==index}" style="width: 100%; height: 100%" @click.prevent="changeCurrentScreen(index)"
          :data-index="index" @dragover="dragover" @drop="drop"
          element-loading-background="rgba(0, 0, 0, 0.8)">
          <!-- 播放视频 -->
          <div v-if="realCameraList[index] && realCameraList[index].liveUrl" class="screen-content">
            <!-- <video src="" controls :id="`video${index}`" style="width: 100%;height: 100%;object-fit: fill" :data-index="index" muted
              crossorigin="anonymous" poster="@/assets/image/map-img/no-video.gif" @error="videoError" @waiting="waiting($event, index)"
              @emptied="emptied(index)" preload="load" @playing="playing(index)"></video> -->

            <video controls autoplay :id="`video${index}`" style="width:100%;height:100%;object-fit:fill" :data-index="index" muted
              crossorigin="anonymous" @playing="playing(index)"></video>

            <i class="el-icon-close close" @click.stop="removeCamera(index)"></i>
            <!-- <i class="bit-stream" @click.stop="bitStreamToggle(index)">切换{{realCameraList[index].videoType?'低':'高'}}码流</i> -->
            <img class="screen-shot-img" :id="`img${index}`" src="" alt="">
          </div>
        </div>
      </div>
    </div>

    <!-- 视频设置 -->
    <el-dialog title="视频播放设置" :visible.sync="showConfigModal" width="45%">
      <el-form ref="form" :model="videoConfigParams" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="轮询时间设置：">
              <el-input style="text-align:center;" type="number" v-model.number="videoConfigParams.pollTime"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="line-height:35px;margin-left:4px">s</el-col>
          <el-col :span="5">
            <el-tooltip class="item" effect="light" content="点击左侧列表网关可轮询播放，设置更换视频的间隔" placement="top">
              <i class="el-icon-question" style="color: #ecb455;font-size: 15px;"></i>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-form-item label="自动刷新播放视频：">
          <el-row>
            <el-col :span="5">
              <el-switch v-model="videoConfigParams.autoFresh" :active-value="1" :inactive-value="2"></el-switch>
            </el-col>
            <el-col :span="5">
              <el-tooltip class="item" effect="light" content="开启后,当前播放视频可定时更新重新拉流(只针对非轮询中的视频)" placement="top">
                <i class="el-icon-question" style="color: #ecb455;font-size: 15px;"></i>
              </el-tooltip>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row v-show="videoConfigParams.autoFresh === 1">
          <el-col :span="12">
            <el-form-item label="刷新时间：">
              <el-input style="text-align:center" type="number" v-model.number="videoConfigParams.displayTime"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="line-height:35px;margin-left:4px">min</el-col>

        </el-row>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showConfigModal = false">取 消</el-button>
        <el-button type="primary" @click="saveConfig">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import ListContent from '../ListContent'
// import { getcamera, picListList, downloadVideo, cameraHandle } from "../cameramap";
// import flvjs from '@/views/common/flv'
import flvjs from '@/views/common/flv-video'
import flvjsO from 'flv.js'
import EventBus from '@/utils/eventBus'
import axios from 'axios'

import * as api from '../../../components/map/api'
import util from '@/libs/util'

export default {
  components: { ListContent,  ElImageViewer },
  data() {
    return {
      playErrorMax: 0,
      maxNum: 0,
      reconnectTimeout: null,
      startAgain: 0,

      maxError: 0,
      lastDecodedFrame: null, // 视频播放

      curerntCamera: null, // 当前相机

      videoLoading: false,
      showConfigModal: false, //视频设置窗口
      videoConfigParams: {},
      videoParams: {
        pollTime: 30, // 轮训时间，默认30s
        autoFresh: 1, // 1是，2否
        displayTime: 2,// 10分钟
      },
      fullScreen: false,
      loadingImg: false,
      visible: false,
      picTime: 25, //最近多少分钟截图
      picTimeInput: '',
      bitStreamType: 0, //0-低码流 1-高码流
      cancel: null,
      isPlaying: false, // 是否正在播放视频
      loadingCamera: [], // 摄像机flvUrl
      showViewer: false,
      curerntSelect: 'four', //几分屏
      currentScreen: 0, //当前选中的摄像机 TODOthis.$refs['form'].clearValidate()有接口了换成camera名字
      currentShotType: 'auto',
      screenList: [
        { name: 1, src: '' },
        { name: 2 },
        { name: 3 },
        { name: 4 },
        { name: 5 },
        { name: 6 },
        { name: 7 },
        { name: 9 },
        { name: 10 },
      ],

      realCameraList: [], // 当前屏幕播放的相机列表
      screenNum: { 'one': 1, 'four': 4, 'six': 6, 'nine': 9 },
      currentDragCamera: '',
      currentCameraList: [],// 某组织下的相机列表
      currentCameraListCopy: [],
      flvInstanceArr: [],
      timer: null,
      isCircleCamera: false, // 摄像机轮询中
      timerBox: {
        timer1: null,
        timer2: null,
        timer3: null,
        timer4: null,
        timer5: null,
        timer6: null,
        timer7: null,
        timer8: null,
        timer9: null,
      },
      timer_refresh: null,
      twentyFiveImg: [],
      manualImg: []
    };
  },

  created() {
    // 添加监听函数
    EventBus.$on('cameraSelected', this.getVideoFlow) // 点击相机
    // EventBus.$on('getCameraList', this.getCameraList)
    EventBus.$on('dragStart', this.dragStart)

    // 初始化摄像机数据
    this.realCameraList = Array.apply(null, { length: 9 })
    this.flvInstanceArr = Array.apply(null, { length: 9 })
    this.cancel = Array.apply(null, { length: 9 })
    this.loadingCamera = Array.apply(null, { length: 9 }).map(item => false)

    // 其他页面跳转
    if (this.$route.query.cameraNum) {
      // this.curerntSelect = 'one';
      // this.getCameraFlow({ cameraNum: this.$route.query.cameraNum, videoType: this.bitStreamType })
    }
  },

  mounted() {
    // this.getVideoConfig() // 获取初始设置

    this.$nextTick(() => {
      window.onload = function() { // todo
        // document.addEventListener('keyup', e => {
        //   // esc键 退出全屏
        //   if (e.keyCode == 27) {
        //     this.fullScreen = false
        //   }
        // })
      }
    })
  },

  computed: {
    // 获取当前选中相机
    getCurrentCameraNumber() {
      if (this.realCameraList[this.currentScreen]) {
        let item = this.realCameraList[this.currentScreen]
        // console.log(item)
        return item
      }
      return {}
    },

    imgList() {
      if (this.currentShotType == 'manual') {
        return [...this.manualImg]
      } else {
        return [...this.twentyFiveImg]
      }
    },

    // 根据当前是否处于轮训中，返回不同重新拉流时间
    timeInterval() {
      return this.isCircleCamera ? 10000 : 20000
    }
  },

  watch: {
    realCameraList(val, oldVal) {
      EventBus.$emit('changeScreen', this.getCurrentCameraNumber)

      // console.log('请求截图啦！')
    },

    // 当前选中屏幕变化时
    currentScreen(val) {
      EventBus.$emit('changeScreen', this.getCurrentCameraNumber)

      // console.log('请求截图：')
    },

    isPlaying(val) {
      EventBus.$emit('changeStatus', val)
    },

    curerntSelect(val, oldval) {
      let valNum = this.screenNum[val]
      let oldvalNum = this.screenNum[oldval]
      if (valNum < oldvalNum) {
        // 由多屏切少屏时，停止掉少屏不展示的多屏的部分的视频
        this.realCameraList.forEach((item, index) => {
          if (index + 1 > valNum && index + 1 <= oldvalNum) {
            if (item) {
              this.removeCamera(index)
            }
          }
        })
      }
    }
  },

  methods: {

    /**
     * 播放视频
     */
    playVideoYeah (flv_url, videoElementId) {
      let player
      if (flvjs.isSupported()) {
        if (player) {
          player.pause();
          player.unload();
          player.detachMediaElement();
          player.destroy();
          player = null;
        }

        let videoElement = document.getElementById(videoElementId)
        player = flvjs.createPlayer(
          {
            // 创建一个新的flv播放器对象
            type: 'flv',
            isLive: true,

            cors: true,
            withCredentials: false,
            enableStashBuffer: false,
            hasVideo: true,
            hasAudio: false,

            url: flv_url,
            config: {
              enableWorker: false,
              autoCleanupSourceBuffer: true,
              autoCleanupMaxBackwardDuration: 5,
              autoCleanupMinBackwardDuration: 2,
              enableStashBuffer: false,
              fixAudioTimestampGap: false,
              stashInitialSize: 128,
            },
          },
          {
            enableWorker: false,
            autoCleanupSourceBuffer: true,
            autoCleanupMaxBackwardDuration: 5,
            autoCleanupMinBackwardDuration: 2,
            enableStashBuffer: false,
            fixAudioTimestampGap: false,
            stashInitialSize: 128,
          }
        )
        player.attachMediaElement(videoElement)
        player.load() // 载入视频
        var promise = player.play() // 播放视频，如果不想要自动播放，去掉本行
        
        // The play() request was interrupted by a call to pause() 还没加载完就播放 会出现这个错误
        if (promise) {
          promise.then(() => {
            player.pause()
            setTimeout(() => {
              player.play()
            }, 400);
          })
        }
      }
      return player
    },

    /**
     * 获取视频流
     */
    getVideoFlow (val) {
      this.maxNum = 0
      this.playVideoing(val, this.currentScreen)
    },
    
    /**
     * 视频初始配置
     */
    getVideoConfig () {
      this.$ajax.get('/manager/info/list').then(res => {
        if (res.rows && res.rows[0]) {
          this.videoParams.pollTime = res.rows[0].pollTime || this.videoParams.pollTime
          this.videoParams.autoFresh = res.rows[0].autoFresh || this.videoParams.autoFresh
          this.videoParams.displayTime = res.rows[0].displayTime || this.videoParams.displayTime
        }
      })
    },

    videoConfig() {
      this.videoConfigParams = { ...this.videoParams }
      this.showConfigModal = true
    },

    stop() {
      this.clearScreen()
    },

    getfullScreen() {
      this.fullScreen = true;
    },

    closeFullScreen() {
      this.fullScreen = false;
    },

    // 截图信息更改时间输入框校验
    checkField(event) {
      let value = event.target.value
      value = value.replace(/\.\d*/g, '')
      if (value > 1440) {
        this.$message('输入值应小于1440')
        event.target.value = 1440
      }
    },

    saveConfig() {
      if (!this.videoConfigParams.pollTime || this.videoConfigParams.pollTime < 10) {
        this.$message({
          type: 'error',
          message: '轮巡时间需大于10s'
        })
        return
      }
      if (this.videoConfigParams.autoFresh === 1) {
        if (!this.videoConfigParams.displayTime || this.videoConfigParams.displayTime < 1) {
          this.$message({
            type: 'error',
            message: '请设置更新时间不得小于1分钟'
          })
          return
        }
      }
      // this.videoConfigParams.userId = this.userId
      this.$ajax.post('/manager/info', this.videoConfigParams).then(res => {
        this.$message({
          type: 'success',
          message: '设置成功'
        })
        this.showConfigModal = false;
        window.location.reload() //刷新页面
      })
    },

    // 清空当前屏幕
    clearScreen() {
      // 清空当前屏幕，清除轮询的定时器
      this.realCameraList.forEach((item, index) => {
        this.removeCamera(index)
      })
      clearInterval(this.timer)
    },

    // 点击左侧摄像机
    getCameraFlow(params, index, sign) {
      // sign：点击单个摄像机sign-single，sign只在 --上次循环，此次点击单个摄像机时作为判断清屏的标识
      index === undefined && (index = this.currentScreen)
      let that = this;
      this.isPlaying = false;
      // console.log(this.loadingCamera[index],'现在是下面的重新赋值，在下面说明是同步');

      // 在取消接口的后面，否则loading值会被覆盖掉
      if (this.isCircleCamera) { // 上一次在循环
        console.log('circle.........................')
        if (sign) { // 本次，若点击单个摄像机，清屏
          this.isCircleCamera = false
          this.clearScreen()
        } else { // 还在循环
          this.removeCamera(index) // 先清掉上一个
          this.loadingCamera[index] = true;
        }
      } else {
        this.removeCamera(index) // 先清掉上一个
        // this.loadingCamera[index] = true;
      }

      this.loadingCamera[index] = true;
      // getVideoStream(parmas)
      this.$ajax.get('/mechanism/server/getVideoStream', {
        params,
        timeout: 15000,
        cancelToken: new axios.CancelToken(function executor(c) {
          that.cancel[index] = c;
        })
      })
        .then(res => {
          this.loadingCamera[index] = false;
          if (res.code == 200) {
            if (typeof res.msg === 'string') {
              let result = JSON.parse(res.msg);
              if (result.code == 200) {
                this.getCamera(result.videoRequestUrl[0], index)

              } else {
                // console.log('baocuo ****1');
                this.loadingCamera.splice(index, 1, false)
                this.$message({
                  showClose: true,
                  message: result.msg,
                  type: 'warning'
                })
                // flv获取失败，轮询状态自动获取下一个,否则重新拉流
                if (this.isCircleCamera) {
                  this.getNextFlv(index)
                } else {
                  // this.getCameraFlow(params, index)
                }
              }
            }
          }
        }).catch(err => {
          if (err.message !== 'cancel') {
            this.loadingCamera[index] = false;
            // this.loadingCamera.splice(this.currentScreen, 1, false);
            // flv获取失败，轮询状态自动获取下一个
            if (this.isCircleCamera) {
              this.getNextFlv(index)
            }
          }
        })
    },

    // 轮询中，播放失败的单个摄像机，自动寻找下一个播放
    getNextFlv(index) {
      console.log('getNextFlv')
      // let item = this.currentCameraListCopy.splice(0, 1)[0]
      // this.getCameraFlow({ cameraNum: item.number, videoType: this.bitStreamType }, index)
    },

    /**
     * 视频流
     */
    async playVideoing (val, index) {
      this.curerntCamera = val
      // this.$store.commit("IS_POWER", val['ptzCtrl']) // 云台控制
      // console.log(val)

      this.getStreamingAgain(val, index)
    },

    /**
     * 销毁目前video
     */
    destroyVideo (player, index) {
      this.loadingCamera[index] = false;
      // 当前这个在播放中，则中止播放，清除当前播放的flv
      if (this.flvInstanceArr[index]) {
          // 关闭视频流
          // var param = {
          //   camId: this.realCameraList[index]['camId'],
          //   playId: this.realCameraList[index]['playId']
          // }
          // api.closeVideo(param).then(res => {

            if (player) {
              player.pause();
              player.unload();
              player.detachMediaElement();
              player.destroy(true);
              player = null;
            }

            this.flvInstanceArr.splice(index, 1, undefined)
          // }).catch(err => {
          //   console.log(err)
          // })
      }
    },

    /**
     * 重新拉流 仅第一次播放视频使用
     */
    async getStreamingAgain(val, index) {

      console.log('getStreamingAgain')
      console.log(val)

      await this.removeCamera(index)

      if (val != null && val != undefined) {
        let camId = util.isNotEmpty(val['camId']) ? val['camId'] : val['camID']

        if (!util.isNotEmpty(camId)) {
          return
        }

        this.loadingCamera[index] = true

        api.getVideo({
          camId: camId,
          type: 1 // 视频流
        }).then(res => {
          this.loadingCamera[index] = false

          this.getCamera(res.data, index)
        }).catch(err => {
          this.loadingCamera[index] = false
          this.maxNum += 1

          if (this.maxNum < 2) {
            setTimeout(() => {
              // this.loadingCamera[index] = true
              this.getStreamingAgain(val, index)
            }, 1 * 1000);
          }
        })
      }
    },

    getCamera(item, index) { // 监控
      this.realCameraList.splice(index, 1, item); // 赋值liveUrl
      this.playCamera(item, index)
    },

    // 播放单个摄像机
    playCamera(item, index) {
      // let dom = document.getElementById(`video${index}`)
      // console.log(dom)

      // http://10.166.147.73:8082/live/12342.live.flv item.liveUrl this.playVideoYeah
      // this.loadingCamera[index] = true;
      this.loadingCamera.splice(index, 1, true)

      let flvInstance = flvjs.playVideo(item.liveUrl, `video${index}`)
      this.flvInstanceArr.splice(index, 1, flvInstance)

      flvInstance.on('error', (errorType, errorDetail, errorInfo) => { // 监听到网络问题，销毁当前的player, 停止播放
        // errType是 NetworkError时，对应errDetail有：Exception、HttpStatusCodeInvalid、ConnectingTimeout、EarlyEof、UnrecoverableEarlyEof
        // errType是 MediaError时，对应errDetail是MediaMSEError

        // console.log('出错啦.....')
        // console.log(errorType)
        // console.log(errorDetail)
        // console.log(errorInfo)

        if (errorInfo != null && errorInfo.code == 404) {
          if (this.reconnectTimeout != null) {
            clearTimeout(this.reconnectTimeout)
          }

          this.reconnectTimeout = setTimeout(() => {
            // 重连
            // this.loadingCamera[index] = true
            this.destroyVideo(this.flvInstanceArr[index], index)
            // this.loadingCamera.splice(index, 1, true)
            this.getStreamingAgain(this.realCameraList[index], index)
          }, 4 * 100);
        } else {
          // console.log('现在啥样了.....')
          // console.log(flvInstance)

          if (flvInstance && flvInstance.e) {
            this.destroyVideo(this.flvInstanceArr[index], index)
            // console.log(this.flvInstanceArr)
          }

          if (this.reconnectTimeout != null) {
            clearTimeout(this.reconnectTimeout)
          }

          this.maxNum += 1

          if (this.maxNum == 6) {
            // 避免一直重新播放 卡死
            this.$modal.msgError('视频播放异常')
            return
          }

          this.reconnectTimeout = setTimeout(() => {
            // 重连
            this.playCamera(item, index)
          }, 6 * 100);
        }
      })

      var testElement = document.getElementById(`video${index}`)

      testElement.addEventListener("progress", () => {
        // if (flvInstance == null || flvInstance.e == null) {
        //   flvInstance = flvjs.playVideo(item.liveUrl, `video${index}`)

        //   if (this.reconnectTimeout != null) {
        //     clearTimeout(this.reconnectTimeout)
        //   }

        //   this.reconnectTimeout = setTimeout(() => {
        //     // 重连
        //     this.lastDecodedFrame = 0
        //     this.destroyVideo(flvInstance, index)
        //     console.log('video 1......')
        //     this.playCamera(item, index)
        //     this.startAgain = 0
        //   }, 3 * 1000);
        //   return
        // }

        let end = flvInstance.buffered.end(0); // 获取当前buffered值(缓冲区末尾)
        let delta = end - flvInstance.currentTime; // 获取buffered与当前播放位置的差值

        // 延迟过大，通过跳帧的方式更新视频
        if (delta > 10 || delta < 0) {
          flvInstance.currentTime = flvInstance.buffered.end(0) - 1;
          return;
        }

        // 追帧
        if (delta > 1) {
          testElement.playbackRate = 1.1;
        } else {
          testElement.playbackRate = 1;
        }
      })

      // 画面卡死 STATISTICS_INFO
      flvInstance.on('statistics_info', res => {
        if (res.decodedFrames != 0) {
          if (this.lastDecodedFrame != res.decodedFrames) {
            this.maxNum = 0
            this.startAgain = 0
            this.lastDecodedFrame = res.decodedFrames
          } else {
            // 避免多次启动
            this.startAgain += 1
            if (this.startAgain == 4) {
              if (this.reconnectTimeout) {
                clearTimeout(this.reconnectTimeout)
              }

              this.reconnectTimeout = setTimeout(() => {
                // 重连
                console.log('video 2.....')

                this.startAgain = 0
                this.playErrorMax += 1
                this.lastDecodedFrame = 0
                this.destroyVideo(this.flvInstanceArr[index], index)
                // this.loadingCamera.splice(index, 1, true)

                if (this.playErrorMax == 3) {
                  this.getStreamingAgain(item, index)
                  this.playErrorMax = 0
                } else {
                  this.playCamera(item, index)
                }
                
              }, 4 * 100);
            }
          }
        }
      })

      // 自动跳帧
      // setInterval(() => {
      //   if (flvInstance.buffered.length) {
      //     let end = flvInstance.buffered.end(0)
      //     let diff = flvInstance.currentTime
      //     if (diff >= 0.5) { // 手动跳帧
      //       flvInstance.currentTime = end
      //     }
      //   }
      // })
      // this.loadingCamera[index] = false;
      setTimeout(() => {
        this.loadingCamera.splice(index, 1, false)
      }, 600);
    },

    // 获取整个组织下的摄像机
    getCameraList(params) {
      getcamera(params).then(res => {
        if (res.code == 200) {
          this.currentCameraList = res.data.treeSelectList.filter(item => item.pictureStatus != 2);
          this.currentCameraListCopy = JSON.parse(JSON.stringify(this.currentCameraList))
          // console.log(this.screenNum[this.curerntSelect], '几分屏');
          // 清空当前屏幕
          this.clearScreen();
          // 组织下相机数目少，不轮询，超过屏幕数量，轮询展示
          if (this.currentCameraListCopy.length <= this.screenNum[this.curerntSelect]) {
            let list = []
            this.currentCameraListCopy.forEach((item, index) => {
              list.push(item)
            })
            this.playCameraList(list)
          } else {
            this.roundCameraList();
            // 轮巡时间
            this.timer = setInterval(() => {
              this.roundCameraList()
            }, this.videoParams.pollTime * 1000)
          }
        }
      })
    },

    // 轮训播放视频
    roundCameraList() {
      this.isCircleCamera = true; // 轮询中
      if (this.currentCameraListCopy.length < this.screenNum[this.curerntSelect]) {
        this.currentCameraListCopy = this.currentCameraListCopy.concat(JSON.parse(JSON.stringify(this.currentCameraList)))
      }
      let list = this.currentCameraListCopy.splice(0, this.screenNum[this.curerntSelect])
      this.playCameraList(list)
    },

    // 播放数组中的视频
    playCameraList(list) {
      // console.log('playCameraList')
      list.forEach((item, index) => {
        this.getCameraFlow({ cameraNum: item.number, videoType: this.bitStreamType }, index)
      })
    },

    // 拖拽开始
    dragStart(params) {
      this.isPlaying = false; // 当前未播放
      this.currentDragCamera = params.result;
      // console.log('drag start')
      // console.log(params)
    },

    dragover(e) {
      // 阻止默认事件，否则拖拽不生效
      e.preventDefault()
    },

    drop(e) {
      // 请求播放url
      // console.log('dropppp')
      // console.log(e)
      this.currentScreen = parseInt(e.target.dataset.index);
      this.playVideoing(this.currentDragCamera, this.currentScreen)
    },

    changeBitType(type) {
      this.bitStreamType = type;
      EventBus.$emit('getBitStreamType', type)
    },

    /**
     * 改变屏数
     */
    changeScreen(screenNum) {
      this.curerntSelect = screenNum
      this.currentScreen = 0;
      EventBus.$emit('getCurrentScreenType', this.curerntSelect)
    },

    /**
     * 点击其它屏幕
     */
    changeCurrentScreen(index) {
      this.currentScreen = index
      this.currentShotType = 'auto'
    },

    changeShotImgType(type) {
      this.currentShotType = type;
    },


    /**
     * 删除视频流
     */
    removeCamera(index) {
      // 当前这个如果还在加载，则将请求终止即可
      // console.log(this.cancel)
      // if (this.loadingCamera[index] === true) {
      //   if (typeof this.cancel[index] === 'function') { // 清除上一个没请求liveUrl回来的接口
      //     this.cancel[index]('cancel');
      //     this.loadingCamera[index] = false;
      //   }
      //   return
      // }

      // this.loadingCamera[index] = false;
      this.loadingCamera.splice(index, 1, false)
      // 当前这个在播放中，则中止播放，清除当前播放的flv
      if (this.flvInstanceArr[index]) {
          // 关闭视频流
          // var param = {
          //   camId: this.realCameraList[index]['camId'],
          //   playId: this.realCameraList[index]['playId']
          // }
          // api.closeVideo(param).then(res => {
            this.realCameraList.splice(index, 1, undefined)
            clearTimeout(this.timerBox[`timer${index + 1}`])

            // flvjs.stopPlayer(this.flvInstanceArr[index])
            var player = this.flvInstanceArr[index]
            if (player) {
              player.pause();
              player.unload();
              player.detachMediaElement();
              player.destroy();
              player = null;
            }

            this.flvInstanceArr.splice(index, 1, undefined)
          // }).catch(err => {
          //   console.log(err)
          // })
      }
    },

    /**
     * 高低码流切换
     */
    bitStreamToggle(index) {
      // console.log('bitStreamToggle')
      let videoType = this.realCameraList[index].videoType ? 0 : 1;

      let cameraNum = this.realCameraList[index].cameraNum;
      this.removeCamera(index)
      let params = { cameraNum, videoType }
      this.getCameraFlow(params, index)
    },

    waiting(e, index) {
      // console.log('waiting')

      // let cameraNum = this.realCameraList[index].camId
      // let bufferRange = e.target;

      // clearTimeout(this.timerBox[`timer${index + 1}`]);

      // this.timerBox[`timer${index + 1}`] = setTimeout(() => {
      //   // 重新获取视频流
      //   this.getStreamingAgain(this.realCameraList[index], index)
      // }, this.timeInterval)
    },

    videoError(e) {
      this.isPlaying = false;
      console.log(e, 'error***********');
    },

    emptied(index) { // 播放中断
      if (index === this.currentScreen) {
        this.isPlaying = false;
      }
    },

    playing(index) {
      if (index === this.currentScreen) {
        this.isPlaying = true;
      }
    },

    closeImg() {
      this.showViewer = false
    },
  },

  beforeDestroy() {
    EventBus.$off('cameraSelected', this.getVideoFlow) // 点击相机
    // EventBus.$off('getCameraList', this.getCameraList)
    EventBus.$off('dragStart', this.dragStart)
    clearTimeout(this.reconnectTimeout)
  }
};
</script>
<style lang="scss" scoped>
.swiper-button-next {
  width: 22px;
  height: 43px;
  right: 0;
  // background: url(~@/assets/image/map-img/next.png) no-repeat center;
}
.swiper-button-prev {
  width: 22px;
  height: 43px;
  left: 0;
  // background: url(~@/assets/image/map-img/prev.png) no-repeat;
  background-size: 100%;
}
// /deep/ 
.swiper-container {
  padding-left: 30px;
  // padding-right: 30px;
}
.close-btn {
  position: absolute;
  right: 15px;
  top: 9px;
  width: 32px;
  height: 34px;
  background: #353438;
  text-align: center;
  line-height: 35px;
  border-radius: 50%;
  z-index: 10;
}
.center-camera {
  width: 58vw;
  height: 80vh;
  padding-right: 10px;
  .screen-menu {
    text-align: right;
    margin-bottom: 5px;
    .menu-num {
      display: inline-block;
      font-size: 14px;
      width: 60px;
      height: 33px;
      text-align: center;
      line-height: 33px;
      margin-left: 6px;
      // background: url(~@/assets/image/map-img/menu-bg.png) no-repeat center;
      cursor: pointer;
    }
    .stream-btn {
      float: left;
    }
    .active {
      background: url(~@/assets/image/map-img/menu-active.png) no-repeat center;
    }
  }
  .full-screen {
    position: fixed !important;
    left: 0;
    top: 0;
    height: 100vh !important;
    width: 100vw !important;
    z-index: 9999;
    background: url(~@/assets/image/map-img/camera-play-bg.png) no-repeat center;
    background-size: 100% 100%;
  }
  .screen {
    height: 55vh;
    width: 100%;
    overflow: hidden;
    position: relative;
    .list {
      float: left;
      width: 50%;
      height: 50%;
      position: relative;
      // background: olive;
      border: 2px solid rgb(51, 152, 255);
      box-sizing: border-box;
      border-collapse: collapse;
      .screen-content {
        width: 100%;
        height: 100%;
        position: relative;
        // background: olive;
        .screen-shot {
          position: absolute;
          right: 10px;
          top: 46%;
          width: 30px;
          height: 30px;
          background: url(~@/assets/image/map-img/screen-shot.png) no-repeat
            center;
          z-index: 3;
          cursor: pointer;
          // display: none;
          transition: all 0.1s ease;
        }
        .close {
          position: absolute;
          right: 2px;
          top: 2px;
          width: 25px;
          height: 25px;
          // background: #353438;
          text-align: center;
          line-height: 25px;
          border-radius: 50%;
          &:hover {
            background: #353438;
          }
        }

        // &:hover .screen-shot{
        //   width: 30px;
        //   // display: block;
        // }
        &:hover .bit-stream {
          display: block;
        }
        .screen-shot-img {
          position: absolute;
          width: 100%;
          height: 100%;
          left: 0;
          top: 0;
          border: 2px dashed #38c03e;
          z-index: 5;
          display: none;
          transition: all 0.1s;
          // transform: scale(0, 0)
        }
        .bit-stream {
          position: absolute;
          right: 7px;
          top: 62%;
          font-size: 12px;
          display: none;
          cursor: pointer;
        }
      }
    }
    .current-screen {
      border: 3px solid #eb8001;
    }
    .list-one {
      width: 100%;
      height: 100%;
    }
    .list-four {
      width: 50%;
      height: 50%;
      &:nth-of-type(1) {
      }
      &:nth-of-type(2) {
        margin-left: -2px;
      }
      &:nth-of-type(3),
      &:nth-of-type(4) {
        margin-top: -2px;
        margin-bottom: -2px;
      }
      &:nth-of-type(4) {
        margin-top: -2px;
        margin-left: -2px;
        margin-bottom: -2px;
      }
    }

    .list-six {
      width: 33.3%;
      height: 33.3%;
      border: 1px solid rgb(51, 152, 255);
      &:nth-of-type(1) {
        width: 66.6%;
        height: 66.5%;
        border-top: 2px solid rgb(51, 152, 255);
        border-left: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(2) {
        border-top: 2px solid rgb(51, 152, 255);
        border-right: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(3),
      &:nth-of-type(6) {
        border-right: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(4) {
        border-left: 2px solid rgb(51, 152, 255);
      }
    }
    .list-nine {
      width: 33.3%;
      height: 33.3%;
      border: 1px solid rgb(51, 152, 255);
      &:nth-of-type(1) {
        border-top: 2px solid rgb(51, 152, 255);
        border-left: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(2) {
        border-top: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(3) {
        border-top: 2px solid rgb(51, 152, 255);
        border-right: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(4) {
        border-left: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(6) {
        border-right: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(7) {
        border-left: 2px solid rgb(51, 152, 255);
        border-bottom: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(8) {
        border-bottom: 2px solid rgb(51, 152, 255);
      }
      &:nth-of-type(9) {
        border-right: 2px solid rgb(51, 152, 255);
        border-bottom: 2px solid rgb(51, 152, 255);
      }
    }
  }
  .screen-shot-title {
    text-align: right;
    margin-top: 10px;
    margin-bottom: 10px;
    .screen-shot-type {
      font-size: 15px;
      padding: 5px;
      border: 1px solid #075282;
      margin-right: 10px;
      cursor: pointer;
    }
    .current-screen-type {
      background: #3398ff;
    }
  }
  .screen-shot-content {
    height: 14vh;

    .no-img {
      text-align: center;
      line-height: 14vh;
    }
  }

  .video-download { // 下载视频
    position: absolute;
    right: 10px;
    top: 30%;
    width: 30px;
    height: 30px;
    background: url(~@/assets/image/map-img/download-video.png) no-repeat center;
    z-index: 3;
    cursor: pointer;
    transition: all 0.1s ease;
  }

  .video-download-bg { // 下载视频
    position: absolute;
    right: 10px;
    top: 30%;
    font-size: 8px;
    background: transparent!important;
    z-index: 3;
  }

  .imColumn {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
</style>

<style lang="scss">
  .el-loading-spinner .circular {
    width: 32px!important;
    height: 32px!important;
  }
</style>
